package com.godofball.medtrack.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.godofball.medtrack.common.Result;
import com.godofball.medtrack.pojo.Drug;
import com.godofball.medtrack.service.DrugService;
import com.godofball.medtrack.service.TypeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequestMapping("/drug")
@RestController
@Slf4j
public class DrugController {

    @Autowired
    private DrugService drugService;

    @Autowired
    private TypeService typeService;

    @GetMapping("/page")
    public Result<Page> page(@RequestParam(value = "page",defaultValue = "1")Integer page,
                             @RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize,
                             String name){
        Page<Drug> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Drug> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(name),Drug::getName,name);
        queryWrapper.orderByDesc(Drug::getSort).orderByDesc(Drug::getUpdateTime);
        drugService.page(pageInfo,queryWrapper);
        return Result.success(pageInfo);
    }

    @PostMapping
    public Result<String> add(@RequestBody Drug drug){
        log.info("add drug:{}",drug);
        drugService.save(drug);
        return Result.success("药品添加失败");
    }

    @GetMapping("/{id}")
    public Result<Drug> getById(@PathVariable("id")Long id){
        log.info("get drug by id:{}",id);
        Drug drug = drugService.getById(id);
        return Result.success(drug);
    }

    @PutMapping
    public Result<String> update(@RequestBody Drug drug){
        log.info("update drug:{}",drug);
        drugService.updateWithDeleteImage(drug);
        return Result.success("药品信息更新成功");
    }

    @GetMapping("/list")
    public Result<List<Drug>> list(){
        List<Drug> drugList = drugService.list();
        LambdaQueryWrapper<Drug> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Drug::getSort).orderByDesc(Drug::getUpdateTime);
        return Result.success(drugList);
    }

}
